import React, { useEffect, useState, useCallback } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faBuilding, 
  faProjectDiagram, 
  faTasks, 
  faCheckCircle,
  faPlus,
  faCalendarAlt,
  faExclamationTriangle,
  faUsers
} from '@fortawesome/free-solid-svg-icons';
import { Card } from '../../components/common/Card';
import { useAuth } from '../../hooks/useAuth';
import { StatCard } from '../../components/dashboard/StatCard';
import { ProjectCard } from '../../components/dashboard/ProjectCard';
import { TaskList } from '../../components/dashboard/TaskList';
import { ActivityItem } from '../../components/dashboard/ActivityItem';
import { dashboardAPI } from '../../api/dashboard';
import { TaskStatus, Priority, ProjectStatus } from '../../types/enums';
import {
  ApiResponse,
  Project,
  Task,
  Notification,
  Workspace,
  WorkspaceMember
} from '../../types/api';
import { useNavigate } from 'react-router-dom';

const Dashboard: React.FC = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [stats, setStats] = useState({
    teamMembers: '0',
    activeProjects: '0',
    pendingTasks: '0',
    completedTasks: '0',
    unreadNotifications: '0'
  });
  const [data, setData] = useState({
    workspaces: [] as Workspace[],
    projects: [] as Project[],
    tasks: [] as Task[],
    notifications: [] as Notification[],
  });
  const [loading, setLoading] = useState({
    workspaces: true,
    projects: true,
    tasks: true,
    notifications: true
  });
  const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>('');
  const [workspaceMembersCount, setWorkspaceMembersCount] = useState<{ [key: string]: number }>({});

  // 加载工作区和成员数据
  const loadWorkspacesAndMembers = useCallback(async () => {
    try {
      const workspacesResponse = await dashboardAPI.getMyWorkspaces();
      if (workspacesResponse.success && Array.isArray(workspacesResponse.data)) {
        setData(prev => ({ ...prev, workspaces: workspacesResponse.data }));
        
        // 获取每个工作区的成员
        const memberPromises = workspacesResponse.data.map(workspace => 
          dashboardAPI.getWorkspaceMembers(workspace.id)
        );
        
        const responses = await Promise.all(memberPromises);
        
        // 计算成员数量
        const membersCountMap: { [key: string]: number } = {};
        const allMembers = new Set<string>();
        
        responses.forEach((response, index) => {
          const workspaceId = workspacesResponse.data[index].id;
          if (response.success && Array.isArray(response.data)) {
            membersCountMap[workspaceId] = response.data.length;
            response.data.forEach(member => allMembers.add(member.userId));
          }
        });
        
        setWorkspaceMembersCount(membersCountMap);
        setStats(prev => ({
          ...prev,
          teamMembers: allMembers.size.toString()
        }));
      }
    } catch (error) {
      console.error('加载工作区和成员数据失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, workspaces: false }));
    }
  }, []);

  // 加载项目数据
  const loadProjects = useCallback(async () => {
    try {
      const response = await dashboardAPI.getProjects({
        status: ProjectStatus.ACTIVE
      });

      if (response.success && Array.isArray(response.data)) {
        setData(prev => ({ ...prev, projects: response.data }));
        setStats(prev => ({
          ...prev,
          activeProjects: response.data.length.toString()
        }));
      }
    } catch (error) {
      console.error('加载项目失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, projects: false }));
    }
  }, []);

  // 加载任务数据
  const loadTasks = useCallback(async () => {
    if (!user?.id) return;

    try {
      const response = await dashboardAPI.getTasks({
        assigneeId: user.id
      });
      
      if (response.success && Array.isArray(response.data)) {
        setData(prev => ({ ...prev, tasks: response.data }));
        
        const pendingTasks = response.data.filter(task => 
          task.status === TaskStatus.TODO || task.status === TaskStatus.IN_PROGRESS
        ).length;
        const completedTasks = response.data.filter(task => 
          task.status === TaskStatus.DONE
        ).length;
        
        setStats(prev => ({
          ...prev,
          pendingTasks: pendingTasks.toString(),
          completedTasks: completedTasks.toString()
        }));
      }
    } catch (error) {
      console.error('加载任务失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, tasks: false }));
    }
  }, [user?.id]);

  // 加载通知数据
  const loadNotifications = useCallback(async () => {
    try {
      const [notificationsResponse, unreadResponse] = await Promise.all([
        dashboardAPI.getNotifications({ limit: 5, isRead: false }),
        dashboardAPI.getUnreadNotificationCount()
      ]);
      
      if (notificationsResponse.success && notificationsResponse.data?.data) {
        setData(prev => ({ 
          ...prev, 
          notifications: notificationsResponse.data.data 
        }));
      }
      
      if (unreadResponse.success && unreadResponse.data) {
        setStats(prev => ({
          ...prev,
          unreadNotifications: unreadResponse.data.count.toString()
        }));
      }
    } catch (error) {
      console.error('加载通知失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, notifications: false }));
    }
  }, []);

  // 初始化数据加载
  useEffect(() => {
    loadWorkspacesAndMembers();
    loadProjects();
    loadTasks();
    loadNotifications();
  }, [loadWorkspacesAndMembers, loadProjects, loadTasks, loadNotifications]);

  // 处理工作区选择
  const handleWorkspaceSelect = (workspaceId: string) => {
    setSelectedWorkspaceId(workspaceId);
    setStats(prev => ({
      ...prev,
      teamMembers: workspaceId 
        ? (workspaceMembersCount[workspaceId] || 0).toString()
        : Object.values(workspaceMembersCount).reduce((sum, count) => sum + count, 0).toString()
    }));
  };

  // 处理任务状态切换
  const handleTaskToggle = async (taskId: string, currentStatus: TaskStatus) => {
    try {
      const newStatus = currentStatus === TaskStatus.DONE 
        ? TaskStatus.IN_PROGRESS 
        : TaskStatus.DONE;
      
      await dashboardAPI.updateTaskStatus(taskId, newStatus);
      await loadTasks(); // 重新加载任务数据
    } catch (error) {
      console.error('更新任务状态失败:', error);
    }
  };

  // 快速功能处理函数
  const handleQuickAction = (action: string) => {
    switch (action) {
      case 'new-project':
        navigate('/projects/new');
        break;
      case 'new-task':
        navigate('/tasks/new');
        break;
      case 'workspace':
        navigate('/workspace');
        break;
      case 'team':
        navigate('/workspace/members');
        break;
      default:
        break;
    }
  };

  return (
    <div className="p-6 space-y-6">
      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard
          icon={<FontAwesomeIcon icon={faUsers} />}
          title="团队成员"
          value={stats.teamMembers}
          color="text-blue-600"
          bgColor="bg-blue-100"
          options={data.workspaces.map(ws => ({
            label: ws.name,
            value: ws.id
          }))}
          onSelect={handleWorkspaceSelect}
        />
        <StatCard
          icon={<FontAwesomeIcon icon={faProjectDiagram} />}
          title="活跃项目"
          value={stats.activeProjects}
          color="text-green-600"
          bgColor="bg-green-100"
        />
        <StatCard
          icon={<FontAwesomeIcon icon={faTasks} />}
          title="待处理任务"
          value={stats.pendingTasks}
          color="text-yellow-600"
          bgColor="bg-yellow-100"
        />
        <StatCard
          icon={<FontAwesomeIcon icon={faExclamationTriangle} />}
          title="未读通知"
          value={stats.unreadNotifications}
          color="text-red-600"
          bgColor="bg-red-100"
        />
      </div>

      {/* 快速功能 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card 
          className="hover:shadow-lg transition-shadow cursor-pointer"
          onClick={() => handleQuickAction('new-project')}
        >
          <div className="flex items-center space-x-4">
            <div className="p-3 rounded-lg bg-blue-100">
              <FontAwesomeIcon icon={faPlus} className="text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">新建项目</h3>
              <p className="text-sm text-gray-500">创建一个新的项目</p>
            </div>
          </div>
        </Card>
        <Card 
          className="hover:shadow-lg transition-shadow cursor-pointer"
          onClick={() => handleQuickAction('new-task')}
        >
          <div className="flex items-center space-x-4">
            <div className="p-3 rounded-lg bg-green-100">
              <FontAwesomeIcon icon={faTasks} className="text-green-600" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">添加任务</h3>
              <p className="text-sm text-gray-500">创建新的任务</p>
            </div>
          </div>
        </Card>
        <Card 
          className="hover:shadow-lg transition-shadow cursor-pointer"
          onClick={() => handleQuickAction('workspace')}
        >
          <div className="flex items-center space-x-4">
            <div className="p-3 rounded-lg bg-yellow-100">
              <FontAwesomeIcon icon={faBuilding} className="text-yellow-600" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">管理工作区</h3>
              <p className="text-sm text-gray-500">工作区设置</p>
            </div>
          </div>
        </Card>
        <Card 
          className="hover:shadow-lg transition-shadow cursor-pointer"
          onClick={() => handleQuickAction('team')}
        >
          <div className="flex items-center space-x-4">
            <div className="p-3 rounded-lg bg-purple-100">
              <FontAwesomeIcon icon={faUsers} className="text-purple-600" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">团队管理</h3>
              <p className="text-sm text-gray-500">管理团队成员</p>
            </div>
          </div>
        </Card>
      </div>

      {/* 项目列表 */}
      <Card title="进行中的项目" 
        className={loading.projects ? 'opacity-50' : ''}
        extra={
          <button className="text-blue-500 hover:text-blue-600 flex items-center">
            <FontAwesomeIcon icon={faPlus} className="mr-1" />
            新建项目
          </button>
        }
      >
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {data.projects.map(project => (
            <ProjectCard 
              key={project.id} 
              {...project} 
              title={project.name}
              description={project.description || ''}
              status={project.status as ProjectStatus}
              priority={project.priority as Priority}
              startDate={project.startDate || ''}
              endDate={project.endDate || ''}
              createdBy={{
                id: project.createdBy,
                username: '',
                email: ''
              }}
            />
          ))}
        </div>
      </Card>

      {/* 任务列表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card title="我的任务" className={loading.tasks ? 'opacity-50' : ''}>
          <TaskList
            tasks={data.tasks.map(task => ({
              id: task.id,
              title: task.title,
              completed: task.status === TaskStatus.DONE,
              dueDate: task.dueDate || '',
              priority: task.priority.toLowerCase() as 'low' | 'medium' | 'high'
            }))}
            onTaskToggle={(taskId) => {
              const task = data.tasks.find(t => t.id === taskId);
              if (task) {
                handleTaskToggle(taskId, task.status as TaskStatus);
              }
            }}
          />
        </Card>

        {/* 最近活动 */}
        <Card title="最近活动" className={loading.notifications ? 'opacity-50' : ''}>
          <div className="space-y-4">
            {data.notifications.map(notification => (
              <ActivityItem
                key={notification.id}
                user={notification.title}
                action={notification.content}
                target=""
                time={new Date(notification.createdAt).toLocaleString()}
              />
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Dashboard; 